package com.lecture.junit.tdd.example;

import javax.security.auth.login.AccountExpiredException;

/**
 * User: Yury
 */
public abstract class LoginServiceState {

    public static final int NUM_LAST_PASSWORDS = 24;
    public static final int LAST_ACTIVITY_MAX_AGE = 45;
    public static final int PASSWORD_MAX_AGE = 30;

    public void login(IAccount acc, String password, LoginService context) throws AccountNotFoundException, AccountAlreadyRevokedException, MustChangePasswordException, AccountExpiredException {

        if (acc.getLastActivityAge() > LAST_ACTIVITY_MAX_AGE) {
            acc.setRevoked(true);
            throw new AccountExpiredException("You haven't been here in a while. Please call support to reactivate your account.");
        }

        if (acc.getPasswordAge() > PASSWORD_MAX_AGE) {
            throw new MustChangePasswordException("Please set a new password.");
        }

        if (acc.passwordMatches(password)) {
            if (acc.isRevoked()) {
                throw new AccountAlreadyRevokedException("Account is already revoked. Please call customer support.");
            }

            acc.setLoggedIn(true);
            acc.updateLastActivityTimestamp();
            context.setState(acc.getUserName(), new FirstFailedAttempt());
        } else {
            dealWithFailedAttempt(acc, context);
        }
    }

    protected abstract void dealWithFailedAttempt(IAccount acc, LoginService context);
}
